local ls = require("luasnip")
local s = ls.snippet
local t = ls.text_node
local i = ls.insert_node
local fmt = require("luasnip.extras.fmt").fmt

ls.add_snippets("c", {
  -- Comment
  s("cm", fmt("/* {} */", { i(1) })),

  -- Printf
  s("st", fmt('printf("{}");\n', { i(1) })),

  -- Common includes
  s("inc", fmt([[
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
{}]], { i(1) })),

  -- Main function
  s("main", fmt([[
int main(int argc, char *argv[]) {{
  {}
  return 0;
}}]], { i(1) })),

  -- Function
  s("func", fmt([[
{} {}({}) {{
  {}
}}]], {
    i(1, "void"),
    i(2, "function_name"),
    i(3, "parameters"),
    i(4, "// code"),
  })),

  -- For loop
  s("for", fmt([[
for ({} {} = {}; {} < {}; {}++) {{
  {}
}}]], {
    i(1, "int"),
    i(2, "i"),
    i(3, "0"),
    i(4, "i"),
    i(5, "n"),
    i(6, "i"),
    i(7, "// code"),
  })),

  -- While loop
  s("while", fmt([[
while ({}) {{
  {}
}}]], {
    i(1, "condition"),
    i(2, "// code"),
  })),

  -- If statement
  s("if", fmt([[
if ({}) {{
  {}
}}]], {
    i(1, "condition"),
    i(2, "// code"),
  })),

  -- If-else statement
  s("ife", fmt([[
if ({}) {{
  {}
}} else {{
  {}
}}]], {
    i(1, "condition"),
    i(2, "// code"),
    i(3, "// code"),
  })),

  -- Switch statement
  s("switch", fmt([[
switch ({}) {{
  case {}:
    {}
    break;
  default:
    {}
}}]], {
    i(1, "variable"),
    i(2, "value"),
    i(3, "// code"),
    i(4, "// code"),
  })),

  -- Struct definition
  s("struct", fmt([[
typedef struct {{
  {}
}} {};]], {
    i(1, "// members"),
    i(2, "struct_name"),
  })),

  -- Malloc with check
  s("mal", fmt([[
{} *{} = ({} *)malloc(sizeof({}) * {});
if ({} == NULL) {{
  fprintf(stderr, "Memory allocation failed\n");
  exit(1);
}}]], {
    i(1, "type"),
    i(2, "ptr"),
    i(3, "type"),
    i(4, "type"),
    i(5, "size"),
    i(6, "ptr"),
  })),

  -- File operations
  s("file", fmt([[
FILE *{} = fopen({}, {});
if ({} == NULL) {{
  fprintf(stderr, "Could not open file\n");
  return 1;
}}]], {
    i(1, "fp"),
    i(2, "\"filename\""),
    i(3, "\"r\""),
    i(4, "fp"),
  })),

  -- Error handling
  s("err", fmt([[
if ({}) {{
  fprintf(stderr, "Error: {}\n");
  return 1;
}}]], {
    i(1, "condition"),
    i(2, "message"),
  })),

  -- Define guard
  s("guard", fmt([[
#ifndef {}_H
#define {}_H

{}

#endif // {}_H]], {
    i(1, "HEADER"),
    i(2, "HEADER"),
    i(3, "// code"),
    i(4, "HEADER"),
  })),
})
